<?php defined('SYSPATH') or die('No direct script access.');
                          
class Photo_Controller extends Controller 
{
	protected $use_cache = FALSE;
	
	public function product($width, $height, $filename)
	{
		$dot = strrpos($filename, '.') > 0 ? '.' : '_';
		
		if (($pos = strrpos($filename, $dot)) !== FALSE)
		{
			$extension = substr($filename, $pos + 1);
			$product_id = substr($filename, 0, $pos);
			
			$filename = realpath('resource/product').'/'.$product_id.'.'.$extension;
			
			$mimetype = Config::item('mimes.'.$extension);
			$mimetype = (isset($mimetype[0])) ? $mimetype[0] : 'image/jpeg';
			$mimetype AND header('Content-type: '.$mimetype);
			
			if(file_exists($filename))
			{
				$path = realpath('photo/product').'/'.$width;
				if( ! is_dir($path) ) mkdir( $path ,  0777);
				$path = realpath('photo/product').'/'.$width.'/'.$height;
				if( ! is_dir($path) ) mkdir( $path ,  0777);
				
				$newfilename = realpath('photo/product').'/'.$width.'/'.$height.'/'.$product_id.'.'.$extension;
				$img = new Image($filename);
				$img->resize($width, $height);
				$img->save($newfilename);
				echo file_get_contents($newfilename);
			}
		}
	}
	
	public function article($width, $filename)
	{
		self::_thumb($width, $width, $filename, $width, 'article');
	}
	
	public function article_category($width, $filename)
	{
		self::_thumb($width, $width, $filename, $width, 'article_category');
	}
	
	public function culture($width, $height, $filename)
	{
		self::_thumb($width, $height, $filename, $width.'/'.$height, 'culture');
	}

	public function education($width, $height, $filename)
	{
		self::_thumb($width, $height, $filename, $width.'/'.$height, 'education');
	}
	
	public function forum($width, $path, $filename)
	{
		self::_thumb($width, $width, $path.'/'.$filename, $width, 'forum');
	}
	
	protected function _thumb($width, $height, $filename, $dirname, $resource)
	{
		$dot = strrpos($filename, '.') > 0 ? '.' : '_';
		
		if (($pos = strrpos($filename, $dot)) !== FALSE)
		{
			$extension = substr($filename, $pos + 1);
			$filename = substr($filename, 0, $pos);
			$despath = DOCROOT.'/photo/'.$resource;
			$newfilename = $despath.'/'.$dirname.'/'.$filename.'.'.$extension;
			
			myfuns::create_folder(dirname($newfilename));
			
			$res_filename = realpath('resource/'.$resource).'/'.$filename.'.'.$extension;
			
			$mimetype = Config::item('mimes.'.$extension);
			$mimetype = (isset($mimetype[0])) ? $mimetype[0] : 'image/jpeg';
			$mimetype AND header('Content-type: '.$mimetype);
			
			if(file_exists($res_filename))
			{
				list($rwidth, $rheight, $rtype, $rattr) = getimagesize($res_filename);
				$img = new Image($res_filename);
				if( $width < $rwidth ) $img->resize($width, $height);
				$img->save($newfilename);
				echo file_get_contents($newfilename);
			}
		}
	}

}